<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">文章管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>文章发布</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- from表单 -->
      <el-form ref="formInfoRef" :model="formInfo" label-width="80px">
        <el-form-item label="标题:">
          <el-input v-model="formInfo.title"></el-input>
        </el-form-item>
        <el-form-item label="类型:">
          <el-radio v-model="formInfo.type" label="1">文章</el-radio>
          <el-radio v-model="formInfo.type" label="2">视频</el-radio>
        </el-form-item>
        <el-form-item label="内容:">
          <!-- 文本框 -->
          <vueEditor
            v-if="formInfo.type == '1'"
            debug
            ref="vRef"
            v-model="formInfo.content"
            :option="{
              fontNames: [
                '宋体',
                '隶书',
                '微软雅黑',
                'Arial',
                'Tahoma',
                'Verdana',
              ],
            }"
          />
          <!-- 上传视频 -->
          <el-upload
            v-else
            :limit="3"
            :on-exceed="handleExceed"
            class="upload-demo"
            :on-success="videoScuess"
            :before-upload="videobeforeAvatarUpload"
            :headers="token"
            name="file"
            :action="imgUrl"
            :on-remove="videohandleRemove"
            :before-remove="videobeforeRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传视频文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="栏目:">
          <el-checkbox
            v-model="checkAll"
            @change="handleCheckAllChange"
            :indeterminate="isIndeterminate"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group
            v-model="checkedCities"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="item in catelist"
              :label="item.id"
              :key="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="封面:">
          <el-upload
            :limit="3"
            :on-exceed="handleExceed"
            list-type="picture-card"
            :action="imgUrl"
            :on-success="handleAvatarSuccess"
            :headers="token"
            :on-remove="coverRemove"
            :file-list="formInfo.cover"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="publish">发送文章</el-button>
    </el-card>
  </div>
</template>

<script>
import axios from "@/utils/index";
import { getCate, getItem } from "@/utils/localDate";
import {
  getpublishAPI,
  getPostDetailByIdAPI,
  getEditpublishAPI,
} from "@/apis/news";
export default {
  data() {
    return {
      token: { Authorization: getItem() },
      // 存放所有栏目的id
      checkboxOption: [],
      // 全选
      checkAll: false,
      // 子选项选中id
      checkedCities: [],
      isIndeterminate: true,
      // 栏目列表  不包含关注头条
      catelist: getCate().splice(2),
      // 图片存放路径
      imgUrl: axios.defaults.baseURL + "/upload",
      dialogVisible: false,
      imageUrl: "",
      //   表单
      formInfo: {
        title: "", //标题
        type: "1", //单选框
        content: "", //内容文本
        categories: [], //栏目id
        cover: [], //封面图片的id
      },
    };
  },
  async created() {
    getCate().forEach((item) => {
      this.checkboxOption.push(item.id);
    });
    // 判断是否有id
    if (this.$route.params.id) {
      const { data: res } = await getPostDetailByIdAPI(this.$route.params.id);
      // type为字符串型
      res.data.type = "" + res.data.type;
      // this.formInfo = res.data;

      for (let k in this.formInfo) {
        this.formInfo[k] = res.data[k];
      }

      // console.log(this.formInfo);
      // 处理栏目
      this.checkedCities = this.formInfo.categories.map((item) => {
        return item.id;
      });
      console.log(this.checkedCities);
      // 处理封面
      // 组件会根据file-list属性进行渲染
      this.formInfo.cover = this.formInfo.cover.map((item) => {
        return { id: item.id, url: item.url };
      });
      // console.log(this.formInfo.cover);
    }
  },
  methods: {
    // 限制图片上传类型
    videobeforeAvatarUpload(file) {
      console.log(file);
      const isMPV4 = file.type === "video/mp4";
      if (!isMPV4) {
        this.$message.error("上传视频只能是 mpv4 格式!");
      }
      return isMPV4;
    },
    // 上传成功
    videoScuess(response) {
      this.$message.success("上传成功");
    },
    videohandleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 删除之前
    videobeforeRemove(file, fileList) {
      // console.log(file, fileList);
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    //   图片上传成功的钩子
    handleAvatarSuccess(response) {
      console.log(response);
      this.$message.success("图片上传成功");
      // 把上传的id存到数据里面
      this.formInfo.cover.push({
        id: response.data.id,
        url: axios.defaults.baseURL + response.data.url,
      });
      console.log(this.formInfo.cover);
    },

    // 删除封面
    coverRemove(file) {
      // console.log(file);
      // console.log(this.formInfo.cover);
      // 删除 要把id删除
      this.formInfo.cover = this.formInfo.cover.filter((item) => {
        return item !== file.response.data.id;
      });
      // console.log(this.formInfo.cover);
    },
    // 超出提示
    handleExceed() {
      this.$message.warning("最多只能上传3个");
    },
    // 点击全选按钮
    handleCheckAllChange(val) {
      // console.log(val);
      // console.log(this.checkboxOption);
      this.checkedCities = val ? this.checkboxOption : [];

      console.log(this.formInfo.categories);
      // console.log(this.checkedCities);
      this.isIndeterminate = false;
    },
    // 点击每一项子项
    handleCheckedCitiesChange(val) {
      console.log(val);
      this.checkAll = val.length === this.checkboxOption.length;
      this.isIndeterminate =
        val.length > 0 && val.length < this.checkboxOption.length;
    },
    // 发布文章
    async publish() {
      if (this.formInfo.title.trim() == "")
        return this.$message.error("标题不能为空");
      // 将栏目数据改造
      this.formInfo.categories = this.checkedCities.map((v) => {
        return { id: v };
      });
      if (this.formInfo.cover.length == 0) {
        this.$message.warning("请至少选择一张封面");
        return;
      }
      // 将封面数据改造
      this.formInfo.cover = this.formInfo.cover.map((v) => {
        return { id: v.id, url: v.url };
      });
      console.log(this.formInfo);
      // 判断是否具有id
      if (this.$route.params.id) {
        const { data: res } = await getEditpublishAPI(
          this.$route.params.id,
          this.formInfo
        );
        if (res.message !== "文章编辑成功")
          return this.$message.error(res.message);
        this.$message.message(res.message);
        this.$router.push("/home/postlist");
        // console.log(res);
      } else {
        const { data: res } = await getpublishAPI(this.formInfo);
        if (res.message !== "文章发布成功")
          return this.$message.error(res.message);
        this.$message.message(res.message);
        console.log(res);
      }
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  //   width: 178px;
  //   height: 178px;
  //   line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
